package com.majia.lib_base.utils;

import static android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;

import com.majia.lib_base.R;
import com.majia.lib_base.databinding.LibLoadingDialogLayoutBinding;


/**
 * @author robin 2023-06-11 created
 */
public class LoadingDialog extends DialogFragment {
    private static LoadingDialog instance;

    public static void showDialog(FragmentManager fm) {
        if (instance == null)
            instance = new LoadingDialog();
        if (fm != null)
            instance.show(fm, "loading_dialog");
    }

    public static void hideDialog() {
        if (instance != null && instance.isAdded())
            instance.dismiss();
    }

    public static LoadingDialog buildDialog() {
        return new LoadingDialog();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NO_FRAME, R.style.lib_dialog);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
//                    dialog.dismiss();
                    return true;
                }
                return false;
            }
        });
        if (dialog.getWindow() != null) {
            dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            dialog.getWindow().setSoftInputMode(SOFT_INPUT_STATE_HIDDEN);
        }
        return dialog;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        LibLoadingDialogLayoutBinding binding = LibLoadingDialogLayoutBinding.inflate(inflater);
        return binding.getRoot();
    }
}
